package com.hua.api.core.framework.sms;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.hua.api.modules.message.domain.SmsSender;
import com.hua.api.modules.message.service.SmsSenderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.util.Date;

@Slf4j
public class SmsSendThread extends Thread {

    private static String Url = "http://106.ihuyi.com/webservice/sms.php?method=Submit";
    private static String APIKEY="32977319565429615312aa2f4e69384c";
    private static String APIID="C40637644";

    private SmsSenderService smsSenderService;
    private SmsSender smsSender;

    public SmsSendThread(SmsSenderService smsSenderService,SmsSender smsSender) {
        this.smsSenderService = smsSenderService;
        this.smsSender = smsSender;
    }

    @Override
    public void run() {
        String phoneNumber = smsSender.getPhoneNumber();
        String context = smsSender.getContext();
        log.info("sendSms(phoneNumber={},context={})", phoneNumber, context);
        boolean success =  sendSms(phoneNumber,context);
        if(success){
            smsSenderService.updateOnSmsSuccess(smsSender.getId());
        }else {
            smsSenderService.updateOnSmsFail(smsSender.getId());
        }
    }

    public static boolean sendSms(String phoneNumber,String content){
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(Url);
        client.getParams().setContentCharset("UTF-8");
        method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");
        Long timel = System.currentTimeMillis()/1000;
        String timestr = timel.toString();
        String src = APIID+APIKEY+phoneNumber+content+timestr;

        String password =  SecureUtil.md5(src);

        NameValuePair[] data = {
                new NameValuePair("account", APIID),
                new NameValuePair("password", password),
                new NameValuePair("mobile", phoneNumber),
                new NameValuePair("content", content),
                new NameValuePair("time", timestr),
                new NameValuePair("format", "json"),
        };
        method.setRequestBody(data);
        try {
            client.executeMethod(method);
            String result = method.getResponseBodyAsString();
            log.info("sendSms result={}",result);
            JSONObject resultJson = JSONObject.parseObject(result);
            Integer code =resultJson.getInteger("code");
            if(2==code){
                return true;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return false;
    }
}
